package com.simpleim.starter.sender;

import com.simpleim.im.common.bean.User;
import com.simpleim.im.common.bean.msg.ProtoMsg;
import com.simpleim.starter.client.ClientSession;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BaseSender {

    private ClientSession session;

    private User user;

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseSender.class);

    public boolean isConnected() {
        return session.isConnected();
    }


    public void sendMsg(ProtoMsg.Message message) {
        if (session.isConnected()) {
            Channel channel = session.getChannel();
            ChannelFuture future = channel.writeAndFlush(message);
            // 执行异步回调
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    if (future.isSuccess()) {
                        sendSuccess(message);
                    } else {
                        sendFail(message);
                    }
                }
            });
        }
    }

    public ClientSession getSession() {
        return session;
    }

    public void setSession(ClientSession session) {
        this.session = session;
    }

    public void sendSuccess(ProtoMsg.Message message) {
        LOGGER.info("发送成功");
    }

    public void sendFail(ProtoMsg.Message message) {
        LOGGER.info("发送失败");
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
